package com.iwhalecloud.bss.kite.cucc.service.collection;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.attr.IUnicomRegionService;
import com.iwhalecloud.bss.kite.cucc.client.api.collection.ICollectionGroupImportService;
import com.iwhalecloud.bss.kite.cucc.client.dto.attr.UnicomRegion;
import com.iwhalecloud.bss.kite.cucc.client.dto.batch.KiteBatchAccept;
import com.iwhalecloud.bss.kite.cucc.client.dto.batch.KiteBatchAcceptDetail;
import com.iwhalecloud.bss.kite.cucc.client.dto.customerOrderInformation.CustOrderInfoRegion;
import com.iwhalecloud.bss.kite.cucc.client.enumerate.OrgLevel;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalServiceOfferConsts;
import com.iwhalecloud.bss.kite.cucc.dataservice.mapper.batch.KiteBatchAcceptDetailMapper;
import com.iwhalecloud.bss.kite.cucc.dataservice.mapper.batch.KiteBatchAcceptMapper;
import com.iwhalecloud.bss.kite.cucc.service.batch.BatchAcceptUtil;
import com.iwhalecloud.bss.kite.dataservice.cache.AttrValueCache;
import com.iwhalecloud.bss.kite.dataservice.entity.AttrValue;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.iwhalecloud.bss.kite.manager.scene.service.operate.OperateChangeService;
import com.ztesoft.bss.common.util.ContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author lyx
 * @version V1.0
 */
@Service
public class CollectionGroupImportService implements ICollectionGroupImportService {

    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Resource
    KiteBatchAcceptMapper kiteBatchAcceptMapper;
    @Resource
    KiteBatchAcceptDetailMapper kiteBatchAcceptDetailMapper;

    @Autowired
    private IOperateSceneInstService operateSceneInstService;

    @Resource(name = "manager.operateChangeService")
    private OperateChangeService operateChangeService;

    @Autowired
    private IUnicomRegionService unicomRegionService;

    @Override
    public String saveColectionGroupMenberUserInfo(String sceneInstId, String custId, String provinceId, String lanId,
        String regionId, String staffId, List<Map<String, Object>> query) {
        KiteSceneInst kiteSceneInst = querySceneInstService.getSceneInst(sceneInstId);
        String serviceOfferId = kiteSceneInst.getServiceOfferId();
        if (KiteStringUtils.equals(LocalServiceOfferConsts.SERVICE_OFFER_COLLECTION_GROUP_ADD, serviceOfferId)) {
            List<Map<String, Object>> addGroupUserInfos = querySceneInstService
                .getExtParameterValue(sceneInstId, "addGroupUserInfos");
            if (KiteListUtils.isNotEmpty(addGroupUserInfos)) {
                addGroupUserInfos.forEach(data -> {
                    String offerId = KiteMapUtils.getString(data, "goods_id");
                    if (KiteStringUtils.isEmpty(offerId)) {
                        return;
                    }
                    List<KiteOfferInst> offerInsts = this.querySceneInstService
                        .listMainOfferInsts(sceneInstId, offerId);
                    if (!KiteListUtils.isEmpty(offerInsts)) {
                        offerInsts.forEach(offerInst -> {
                            this.querySceneInstService.listProdInstsFromOfferInst(custId, offerInst.getOfferInstId())
                                .forEach(prodInst -> {
                                    //this.operateSceneInstService.deleteProdInst(sceneInstId, prodInst.getProdInstId());
                                    operateChangeService.setDeleteInstChange(kiteSceneInst, prodInst, false, null, "");
                                    prodInst.setActionType(ActionType.D);
                                    prodInst.setOriginalActionType(ActionType.K);
                                    operateSceneInstService.addInst(sceneInstId, prodInst);
                                });
                            //this.operateSceneInstService.deleteMainOfferInst(sceneInstId, offerInst.getOfferInstId());
                            operateChangeService.setDeleteInstChange(kiteSceneInst, offerInst, false, null, "");
                            offerInst.setActionType(ActionType.D);
                            offerInst.setOriginalActionType(ActionType.K);
                            operateSceneInstService.addInst(sceneInstId, offerInst);
                            //operateSceneInstService.addMainOfferInst(sceneInstId, offerInst);
                        });
                    }
                });
                addGroupUserInfos.clear();
            }
            operateSceneInstService.putExtParameter(sceneInstId, "addGroupUserInfos", query);
        }
        if (KiteStringUtils.equals(LocalServiceOfferConsts.SERVICE_OFFER_COLLECTION_GROUP_DEL, serviceOfferId)) {
            List<Map<String, Object>> delGroupUserInfos = querySceneInstService
                .getExtParameterValue(sceneInstId, "delGroupUserInfos");
            checkDeleteUserInfo(delGroupUserInfos, query);
            if (KiteListUtils.isNotEmpty(delGroupUserInfos)) {
                delGroupUserInfos.forEach(data -> {
                    String offerId = KiteMapUtils.getString(data, "goods_id");
                    if (KiteStringUtils.isEmpty(offerId)) {
                        return;
                    }
                    List<KiteOfferInst> offerInsts = this.querySceneInstService
                        .listMainOfferInsts(sceneInstId, offerId);
                    if (!KiteListUtils.isEmpty(offerInsts)) {
                        offerInsts.forEach(offerInst -> {
                            this.querySceneInstService.listProdInstsFromOfferInst(custId, offerInst.getOfferInstId())
                                .forEach(prodInst -> {
                                    //this.operateSceneInstService.deleteProdInst(sceneInstId, prodInst.getProdInstId());
                                    operateChangeService.setDeleteInstChange(kiteSceneInst, prodInst, false, null, "");
                                    prodInst.setActionType(ActionType.D);
                                    prodInst.setOriginalActionType(ActionType.K);
                                    operateSceneInstService.addInst(sceneInstId, prodInst);
                                });
                            //this.operateSceneInstService.deleteMainOfferInst(sceneInstId, offerInst.getOfferInstId());
                            operateChangeService.setDeleteInstChange(kiteSceneInst, offerInst, false, null, "");
                            offerInst.setActionType(ActionType.D);
                            offerInst.setOriginalActionType(ActionType.K);
                            operateSceneInstService.addInst(sceneInstId, offerInst);
                            //operateSceneInstService.addMainOfferInst(sceneInstId, offerInst);
                        });
                    }
                });
                delGroupUserInfos.clear();
            }
            operateSceneInstService.putExtParameter(sceneInstId, "delGroupUserInfos", query);
        }
        // 不需要传成员的商品实例
        // this.addMemberOfferInst(sceneInstId, custId, provinceId, lanId, regionId, staffId, query);
        return null;
    }

    /**
     * 选择成员退出时校验，选择的成员，归集集团userId必须一致
     *
     * @param delGroupUserInfos
     * @param query
     */
    private void checkDeleteUserInfo(List<Map<String, Object>> delGroupUserInfos, List<Map<String, Object>> query) {
        if (KiteListUtils.isEmpty(delGroupUserInfos) || KiteListUtils.isEmpty(query)) {
            return;
        }
        // 虽然query是个list，但其实前台页面是一条一条选择的，所以只需要判断最新选择那条就行
        Map<String, Object> newSelectUserInfo = query.get(query.size() - 1);
        // 已存在的记录，默认是归集集团userId是一致的
        Map<String, Object> selectUserInfo = delGroupUserInfos.get(0);
        if (!KiteStringUtils.equals(KiteMapUtils.getString(selectUserInfo, "PRIMARY_USER_ID"),
            KiteMapUtils.getString(newSelectUserInfo, "PRIMARY_USER_ID"))) {
            ErrorConsts.BUSI_COMMON_ERROR.throwOut("选择的成员与已选择成员的归集集团userID不一致，请重新选择", "选择的成员与已选择成员的归集集团userID不一致，请重新选择");
        }
    }

    @Override
    public PageInfo<Map<String, Object>> queryKiteGroupBatchLog(Map<String, Object> query) {
        Integer pageNum = (Integer) query.get("pageNum");
        Integer pageSize = (Integer) query.get("pageSize");
        PageHelper.startPage(pageNum, pageSize);
        List<Map<String, Object>> list = kiteBatchAcceptMapper.queryKiteBatchAccept(query);
        list.forEach(map -> {
            Integer importNum = KiteMapUtils.getInteger(map, "import_num");
            String batchId = KiteMapUtils.getString(map, "batch_id");
            Example example = new Example(KiteBatchAcceptDetail.class);
            example.createCriteria().andEqualTo("batchId", batchId).andEqualTo("statusCd", "1100");
            int failCount = kiteBatchAcceptDetailMapper.selectCountByExample(example);
            example.clear();
            example.createCriteria().andEqualTo("batchId", batchId).andEqualTo("statusCd", "1000");
            int todoCount = kiteBatchAcceptDetailMapper.selectCountByExample(example);
            example.clear();
            example.createCriteria().andEqualTo("batchId", batchId).andEqualTo("checkStatus", "1100");
            failCount += kiteBatchAcceptDetailMapper.selectCountByExample(example);
            example.clear();
            example.createCriteria().andEqualTo("batchId", batchId).andEqualTo("statusCd", "1200");
            int succCount = kiteBatchAcceptDetailMapper.selectCountByExample(example);
            map.put("deal_result", "总数："+importNum+"条，成功：" + succCount + "条，失败：" + failCount + "条");
            // 导入类型为批量受理，且处理失败的条数大于1
            if (KiteStringUtils.equalsAny(KiteMapUtils.getString(map, "import_type"), "4000", "5000", "7100", "7200")
                && failCount > 0
                && KiteStringUtils.equals(KiteMapUtils.getString(map, "create_staff"),
                    ContextUtil.getLoginInfo().getStaffInfo().getStaffId().toString())) {
                map.put("recommitable", "T");
            }
        });

        return new PageInfo<>(list);
    }

    @Override
    public PageInfo<Map<String, Object>> queryKiteGroupDetailLog(Map<String, Object> query) {
        List<Map<String, Object>> detailList = new ArrayList<>();
        Integer pageNum = (Integer) query.get("pageNum");
        Integer pageSize = (Integer) query.get("pageSize");
        PageHelper.startPage(pageNum, pageSize);
        List<KiteBatchAcceptDetail> kiteBatchAcceptDetails = kiteBatchAcceptDetailMapper
            .queryKiteBatchAcceptDetail(query);
        KiteBatchAccept kiteBatchAccept = kiteBatchAcceptMapper.selectByPrimaryKey(new KiteBatchAccept().setBatchId(kiteBatchAcceptDetails.get(0).getBatchId()));
        for (KiteBatchAcceptDetail kiteBatchAcceptDetail : kiteBatchAcceptDetails) {
            Map<String, Object> detailMap = new HashMap<>();
//            detailMap.put("checkResult", kiteBatchAcceptDetail.getCheckResult());
//            detailMap.put("dealDesc", kiteBatchAcceptDetail.getDealResult());
            detailMap.put("校验结果", kiteBatchAcceptDetail.getCheckResult());
            detailMap.put("处理结果", kiteBatchAcceptDetail.getDealResult());
            String attrJson = kiteBatchAcceptDetail.getAttrJson();
            if (KiteStringUtils.isNotEmpty(attrJson)) {
                Map<String, String> attrMap;
                if (KiteStringUtils.equalsAny(kiteBatchAccept.getImportType(), "7100", "7200")) {
                    attrMap = BatchAcceptUtil.delBatchNodeLog(kiteBatchAcceptDetail.getAttrJson());
                }
                else {
                    List<KiteAttr> kiteAttrs = JSONObject.parseArray(attrJson, KiteAttr.class);
                    attrMap = kiteAttrs.stream()
                        .collect(Collectors.toMap(KiteAttr::getCname, KiteAttr::getValue, (o, n) -> n));
                    if (KiteStringUtils.isNotEmpty(KiteMapUtils.getString(attrMap, "telecomType"))) {
                        AttrValue attrValue = AttrValueCache
                            .getAttrValue("20210304001", KiteMapUtils.getString(attrMap, "telecomType"));
                        attrMap.put("telecomType", attrValue.getAttrValueName());
                    }
                }
                detailMap.putAll(attrMap);
            }
            detailList.add(detailMap);
        }
        PageInfo<KiteBatchAcceptDetail> pageInfo = new PageInfo<>(kiteBatchAcceptDetails);
        PageInfo<Map<String, Object>> resultPage = new PageInfo<>(detailList);
        resultPage.setTotal(pageInfo.getTotal());
        return resultPage;
    }

    @Override
    public List<Map<String, Object>> queryKiteGroupBatchLogForList(String batchId) {
        return kiteBatchAcceptDetailMapper.queryKiteGroupBatchLogForList(batchId);
    }

    @Override
    public CustOrderInfoRegion getProvince() {
        /**
         * 归属地属性根据工号级别不同，枚举值展示不同，譬如：
         * 集团工号可以查询全国的的用户，归属地的下拉框支持选择所有省分和地市，地市可允许为空；
         * 省级工号只能查询当前登录工号对应省分（包含本省所有地市及区县）的用户，归属地的下拉框省分默认当前登录工号对应省分，置灰不允许编辑，归属地的下拉框地市展示对应省分下的所有地市，允许编辑；
         * 市级工号只能查询当前登录工号对应地市（包含本地市及区县）的用户，归属地的下拉框省分默认当前登录工号对应省分，置灰不允许编辑，归属地的下拉框地市展示默认当前登录工号对应地市，置灰不允许编辑。
         */
        List<UnicomRegion> unicomRegions = unicomRegionService.listSubRegion("");
        CustOrderInfoRegion custOrderInfoRegion = new CustOrderInfoRegion();
        Long orgLevel = ContextUtil.getLoginInfo().getOrgInfo().getOrgLevel();
        String provinceCode = ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr();
        if (OrgLevel.BASE.getOrgLevel().equals(orgLevel)) {
            custOrderInfoRegion.setIsEdit(KeyConsts.IFTRUE_T);
        } else {
            custOrderInfoRegion.setIsEdit(KeyConsts.IFTRUE_F);
//            unicomRegions.removeIf(unicomRegion -> !KiteStringUtils.isEqual(unicomRegion.getRegionCode(), provinceCode));
            if (unicomRegions.stream().anyMatch(unicomRegion -> KiteStringUtils.isEqual(unicomRegion.getRegionCode(), provinceCode))) {
                custOrderInfoRegion.setDefaultValue(provinceCode);
            }
        }
        custOrderInfoRegion.setRegions(unicomRegions);
        return custOrderInfoRegion;
    }

    @Override
    public CustOrderInfoRegion getCity(String provinceCode) {
        CustOrderInfoRegion custOrderInfoRegion = new CustOrderInfoRegion();
        if (KiteStringUtils.isEmpty(provinceCode)) {
            return custOrderInfoRegion;
        }
        List<UnicomRegion> unicomRegions = unicomRegionService.listSubRegion(provinceCode);
        Long orgLevel = ContextUtil.getLoginInfo().getOrgInfo().getOrgLevel();
        String cityCode = ContextUtil.getLoginInfo().getUserInfo().getPostLanId();
        if (OrgLevel.BASE.getOrgLevel().equals(orgLevel) || OrgLevel.PROVINCE.getOrgLevel().equals(orgLevel)) {
            custOrderInfoRegion.setIsEdit(KeyConsts.IFTRUE_T);
        } else {
            custOrderInfoRegion.setIsEdit(KeyConsts.IFTRUE_F);
//            unicomRegions.removeIf(unicomRegion -> !KiteStringUtils.isEqual(unicomRegion.getRegionCode(), cityCode));
            if (unicomRegions.stream().anyMatch(unicomRegion -> KiteStringUtils.isEqual(unicomRegion.getRegionCode(), cityCode))) {
                custOrderInfoRegion.setDefaultValue(cityCode);
            }
        }
        custOrderInfoRegion.setRegions(unicomRegions);
        return custOrderInfoRegion;
    }
}
